package com.cloudeasy.core.bean;

import com.cloudeasy.core.properties.SecurityProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * Jwt解析器
 */
@Component
public class JwtParser {
    private final SecurityProperties securityProperties;

    public JwtParser(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    /**
     * 解析{@link Authentication}
     *
     * @param authentication 要解析的{@link Authentication}
     * @return {@link Jws < Claims >}
     */
    public Jws<Claims> parse(Authentication authentication) {
        OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) authentication.getDetails();
        String token = oAuth2AuthenticationDetails.getTokenValue();
        return Jwts.parser()
                .setSigningKey(securityProperties.getOauth2().getJwtSigningKey().getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token);
    }

    /**
     * 从body中获取指定key的数据
     *
     * @param authentication 要解析的{@link Authentication}
     * @param key            key值
     * @return {@link Object}
     */
    public Object getOnBody(Authentication authentication, String key) {
        Jws<Claims> claimsJws = parse(authentication);
        return claimsJws.getBody().get(key);
    }
}
